//
//  ViewController.swift
//  闭包
//
//  Created by Summer on 2017/11/3.
//  Copyright © 2017年 Summer. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        // Test1
        /*
        let digitNames = [
            0: "Zero", 1: "One", 2: "Two",   3: "Three", 4: "Four",
            5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
        ]
        let numbers = [16, 58, 510]
        
        let stringsArray = numbers.map {
            (number) -> String in
            var number = number
            var output = ""
            while number > 0 {
                output = digitNames[number % 10]! + output
                number /= 10
            }
            return output
        }
        */
        
        
        
        
        // Test2
        let rect = CGRect(x: 0, y: 20, width: view.bounds.width, height: 44)
        let sv = scrollView(frame: rect, nummber: { () -> Int in
            return 20
        }) { (index) -> UILabel in
            let label = UILabel()
            label.text = "Hello\(index)"
            label.textColor = UIColor.red
            label.font = UIFont.systemFont(ofSize: 18)
            label.sizeToFit()
            label.font = UIFont.systemFont(ofSize: 14)
            return label
        }
        // swift中不用写 self. 在需要的时候写
        view.addSubview(sv)
    }
    
    
    /// 创建UIScrollView
    ///
    /// - Parameter frame: frame
    /// - Returns: scrollView
    /*
         需求：标签的个数和内容都由闭包来实现
         闭包的返回值用来接收闭包的执行结果，继续后续的代码
         闭包的参数：用来将内容传递给闭包内部去执行
     
     */
    func scrollView(frame:CGRect, nummber: ()->Int, labelOfIndex: (_ index: Int)->UILabel) -> UIScrollView {
        // 1.实例化scrollview，指定位置frame
        let sv = UIScrollView(frame: frame)
        sv.backgroundColor = UIColor.lightGray
        
        // 2.指定标签label数量
        // 执行闭包number()，获得返回值为10，继续后续的代码
        let count = nummber()
        print("标签数量：\(count)")
        
        // 3.知道标签内容，添加到scrollView
        // 遍历count
        
        let margin:CGFloat = 10
        var labelX = margin
        
        
        for i in 0..<count {
            // 执行闭包，获得label
            let label = labelOfIndex(i)
            
            label.frame = CGRect(x: labelX, y: 0, width: label.bounds.width, height: frame.height)
            sv.addSubview(label)
            labelX += label.bounds.width
        }
        sv.contentSize = CGSize(width: labelX + margin, height: 0)
        // 4.返回scrollView
        
        return sv
    }
    

}

